import React, { Component } from 'react';
import {
  Button,
  Modal,
  Select,
  Form,
  Row,
  Col,
  Input,
  DatePicker,
  Radio,
  Tabs,
  Tree,
  message,
  Tag,
} from 'antd';
const { TabPane } = Tabs;
const { TextArea } = Input;
const { TreeNode } = Tree;
import moment from 'moment';
import ReportCard from '@/components/ReportCard';

import style from './index.css';
import BaseComponent from '@/components/BaseComponent';
import { connect } from 'dva';

@connect(({ user }) => ({
  // data: risk.riskData,
  currentUser: user.currentUser,
}))
export default class index extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      activeKey: '1',
      treeListData: [],
      form: {},
      tag1: [],
      tag2: [],
      tag3: [],
      tag4: [],
      tag5: [],
      njzd: { '1': [], '2': [], '3': [], '4': [], '5': [] },
      showTags: [],
      acheData: [],
      dyeData: [],
      hpData: [],
      isHjData: [],
      hpjcjgData: [],
      reportFilePath: undefined,
    };
  }

  showModal = () => {
    this.findAllDictName();
    this.setState({
      visible: true,
    });
  };

  handleOk = () => {
    // const njzd = this.state.njzd.join(',');
    // this.setState((params) => ({
    //     form: {
    //         ...params.form,
    //         id: this.props.record.id,
    //         njzd: njzd,
    //         skip: '1',
    //         user: this.props.currentUser.id,
    //     }
    // }), () => {
    //     this.updateRecord(this.state.form)
    //     this.setState({
    //         visible: false,
    //     });
    // });

    this.setState({
      visible: false,
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };
  handleNjTabChange = key => {
    this.setState({ activeKey: key });
  };
  onCheck = checkedKeys => {
    this.setState({ njzd: checkedKeys }, () => {
      console.log('onCheck', this.state.njzd);
    });
  };
  handleUploadBefore = (file, fileList) => {
    this.setState({ isUploading: true }, () => {
      this.hide = this.loadingMessage('正在上传...');
    });
    return true;
  };
  handleBlUploadChange = ({ info }) => {
    if (info.file.status !== 'uploading') {
      this.setState(
        {
          fileList: info.fileList,
        },
        () => {}
      );
    }
    if (info.file.status === 'done') {
      const response = info.file.response;
      const {
        data: { filePath, originalFilename },
      } = response;
      const arr = filePath.split('/');
      // 文件前缀
      const prefix = arr[arr.length - 2];
      const url = `${prefix}/${originalFilename}`;

      this.setState(params => ({
        form: {
          ...params.form,
          reportFilePath: filePath,
          reportFileUrl: url,
        },
        isUploading: false,
      }));
      if (this.hide) {
        this.hide();
      }
      this.successMessage('上传成功');
    } else if (info.file.status === 'error') {
      this.errorMessage('文件上传出错,请联系管理员');
    }
  };

  nameChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        name: value,
      },
    }));
  };
  sfzChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        sfz: value,
      },
    }));
  };

  screeningIdChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        screeningId: value,
      },
    }));
  };

  phoneChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        phone: value,
      },
    }));
  };
  njNumChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        njNum: value,
      },
    }));
  };

  acheChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        ache: value,
      },
    }));
  };

  dyeChange = value => {
    this.setState(params => ({
      form: {
        ...params.form,
        dye: value,
      },
    }));
  };
  isHjChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        isHj: value,
      },
    }));
  };

  njzlTimeChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState(params => ({
      form: {
        ...params.form,
        njzlTime: dateString,
      },
    }));
  };

  hpChange = value => {
    this.setState(params => ({
      form: {
        ...params.form,
        hp: value,
      },
    }));
  };

  hpjcjgChange = value => {
    this.setState(params => ({
      form: {
        ...params.form,
        hpjcjg: value,
      },
    }));
  };

  picNumsChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        picNums: value,
      },
    }));
  };
  njStaffChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        njStaff: value,
      },
    }));
  };
  verifyStaffChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        verifyStaff: value,
      },
    }));
  };

  //字典
  findAllDictName = () => {
    this.execHttp('treatmentList/findAllDictName').then(resp => {
      if (resp && resp.success) {
        const acheData = resp.data.ache.map(({ dictValue, dictName }) => {
          return { value: dictValue, label: dictName };
        });
        const isHjData = resp.data.is_hj.map(({ dictValue, dictName }) => {
          return { value: dictValue, label: dictName };
        });
        // 将树形结构保存为数组结构
        const treeListData = [
          ...this.treeToList(JSON.parse(JSON.stringify(resp.data.tag1))),
          ...this.treeToList(JSON.parse(JSON.stringify(resp.data.tag2))),
          ...this.treeToList(JSON.parse(JSON.stringify(resp.data.tag3))),
          ...this.treeToList(JSON.parse(JSON.stringify(resp.data.tag4))),
          ...this.treeToList(JSON.parse(JSON.stringify(resp.data.tag5))),
        ];
        this.setState(
          {
            tag1: resp.data.tag1,
            tag2: resp.data.tag2,
            tag3: resp.data.tag3,
            tag4: resp.data.tag4,
            tag5: resp.data.tag5,
            acheData: acheData,
            dyeData: resp.data.dye,
            hpData: resp.data.Hp,
            isHjData: isHjData,
            hpjcjgData: resp.data.hpjcjg,
            treeListData,
          },
          () => {
            this.findDataById();
          }
        );
      }
    });
  };

  //保存
  updateRecord = from => {
    this.execHttp('crowdDataReport/updateRecord', {
      ...from,
    }).then(resp => {
      if (resp && resp.success) {
        message.success(resp.message);
        this.props.getDataByPage();
      } else {
        message.error(resp.message);
      }
    });
  };

  /**详情*/
  findDataById = () => {
    this.execHttp('formalDatabase/findDataById', {
      id: this.props.record.id,
    }).then(resp => {
      if (resp && resp.success) {
        this.setState({
          form: resp.data.response,
        });
        if (resp.data.response.njzd) {
          const { njzd, tag1, tag2, tag3, tag4, tag5 } = this.state;
          let requestData = resp.data.response.njzd.split(',');
          // 数组去重   处理脏数据
          requestData = new Set(requestData);
          requestData = Array.from(requestData);

          const tem = [[...tag1], [...tag2], [...tag3], [...tag4], [...tag5]];
          requestData.forEach(element => {
            tem.forEach((elementData, index) => {
              if (this.recursion(element, elementData)) {
                njzd[index + 1].push(element);
              }
            });
          });
          this.setState(
            {
              njzd,
            },
            () => {
              const showTags = this.getAllSelectTag();
              this.setState({
                showTags,
              });
            }
          );
        }
      }
    });
  };

  //  tree check
  /**
   *
   * @param {*} options  tree结构中的选项
   * @returns
   */
  onCheckHandle = options => {
    return (checkedkeys, e) => {
      let { njzd, activeKey, showTags, treeListData } = this.state;
      njzd[activeKey] = checkedkeys;

      // 当前点击选择的选项
      const current = checkedkeys[checkedkeys.length - 1];

      // 每个树下面的排他项的值
      const repelOptionValue = options[0].props.children[0].key;
      const repelOption = options[0].props.children[0];
      console.log(repelOption);
      if (checkedkeys.indexOf(repelOptionValue) >= 0) {
        njzd[activeKey] = [repelOptionValue];
      }
      showTags = this.getAllSelectTag();

      this.setState({
        njzd,
        showTags,
      });
    };
  };

  // 获取所有选择的病状
  getAllSelectTag() {
    const { njzd, treeListData } = this.state;
    let showTags = [];
    for (const key in njzd) {
      const item = njzd[key];
      for (let index = 0; index < item.length; index++) {
        const element = item[index];
        treeListData.forEach(el => {
          if (el.value === element) {
            showTags.push(el.title);
          }
        });
      }
    }
    return showTags;
  }

  recursion = (element, elementData) => {
    let found = false;
    elementData.forEach(tar => {
      if (element == tar.id) {
        found = true;
      } else {
        if (tar.children && tar.children.length > 0) {
          const childFound = this.recursion(element, tar.children);
          if (childFound) {
            found = true;
            return;
          }
        }
      }
    });
    return found;
  };

  treeToList = data => {
    let res = [];
    const dfs = tree => {
      tree.forEach(item => {
        if (item.children) {
          dfs(item.children);
          delete item.children;
        }
        res.push(item);
      });
    };
    dfs(data);

    return res;
  };

  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} />;
    });

  render() {
    const { visible, tag1, tag2, tag3, tag4, tag5, njzd, showTags } = this.state;
    const ceshi = [2];
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    let treeOptions = [
      this.renderTreeNodes(tag1),
      this.renderTreeNodes(tag2),
      this.renderTreeNodes(tag3),
      this.renderTreeNodes(tag4),
      this.renderTreeNodes(tag5),
    ];

    return (
      <div style={{ display: 'inline-block' }}>
        <Button type="primary" style={{ marginLeft: '10px' }} onClick={this.showModal}>
          内镜
        </Button>
        <Modal
          title="内镜检查"
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={1500}
        >
          <Form {...formItemLayout}>
            <Row gutter={16}>
              <Col span={6}>
                <Form.Item label="姓名">
                  <Input
                    placeholder="姓名"
                    value={this.state.form.name}
                    disabled
                    onChange={this.nameChange}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="身份证">
                  <Input
                    placeholder="身份证号码"
                    value={this.state.form.sfz}
                    disabled
                    onChange={this.sfzChange}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="调查对象ID号">
                  <Input
                    placeholder="调查对象ID号"
                    value={this.state.form.screeningId}
                    disabled
                    onChange={this.screeningIdChange}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="电话">
                  <Input
                    placeholder="电话"
                    value={this.state.form.phone}
                    disabled
                    onChange={this.phoneChange}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={6}>
                <Form.Item label="内镜号">
                  <Input
                    placeholder="内镜号"
                    value={this.state.form.njNum}
                    disabled
                    onChange={this.njNumChange}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="是否无痛">
                  <Radio.Group
                    value={this.state.form.ache}
                    options={this.state.acheData}
                    onChange={this.acheChange}
                    disabled
                    style={{ width: 750 }}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="染色类型">
                  <Select
                    allowClear
                    value={this.state.form.dye}
                    onChange={this.dyeChange}
                    disabled
                    style={{ width: 200 }}
                    placeholder="请选择食管最高病理诊断代码"
                  >
                    {this.state.dyeData.map(item => (
                      <Select.Option key={item.dictValue}>
                        {'(' + item.dictValue + ')' + item.dictName}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="是否活检">
                  <Radio.Group
                    options={this.state.isHjData}
                    disabled
                    onChange={this.isHjChange}
                    value={this.state.form.isHj}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={6}>
                <Form.Item label="内镜诊疗日期">
                  <DatePicker
                    style={{ width: 200 }}
                    disabled
                    showTime
                    format="YYYY-MM-DD"
                    value={
                      this.state.form.njzlTime === null
                        ? this.state.form.njzlTime
                        : moment(this.state.form.njzlTime, 'YYYY-MM-DD')
                    }
                    onChange={this.njzlTimeChange}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="hp">
                  <Select
                    allowClear
                    value={this.state.form.hp}
                    onChange={this.hpChange}
                    style={{ width: 200 }}
                    disabled
                    placeholder="请选择食管最高病理诊断代码"
                  >
                    {this.state.hpData.map(item => (
                      <Select.Option key={item.dictValue}>
                        {'(' + item.dictValue + ')' + item.dictName}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="Hp检测方法">
                  <Select
                    allowClear
                    value={this.state.form.hpjcjg}
                    onChange={this.hpjcjgChange}
                    style={{ width: 200 }}
                    disabled
                    placeholder="请选择食管最高病理诊断代码"
                  >
                    {this.state.hpjcjgData.map(item => (
                      <Select.Option key={item.dictValue}>
                        {'(' + item.dictValue + ')' + item.dictName}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="图片数量">
                  <Input
                    placeholder="图片数量"
                    value={this.state.form.picNums}
                    onChange={this.picNumsChange}
                    style={{ width: 200 }}
                    disabled
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={6}>
                <Form.Item label="内镜诊断医师">
                  <Input
                    placeholder="内镜诊断医师"
                    value={this.state.form.njStaff}
                    onChange={this.njStaffChange}
                    style={{ width: 200 }}
                    disabled
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="内镜审核医师">
                  <Input
                    placeholder="内镜审核医师"
                    value={this.state.form.verifyStaff}
                    onChange={this.verifyStaffChange}
                    style={{ width: 200 }}
                    disabled
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12}>
                <Form.Item label="内镜诊断">
                  <div
                    style={{ display: 'flex', marginLeft: '48px', width: '100%', flexWrap: 'wrap' }}
                  >
                    {showTags.map((item, index) => {
                      return (
                        <Tag
                          color="#87d068"
                          key={index}
                          style={{ marginLeft: '5px', marginTop: '5px' }}
                        >
                          {item}
                        </Tag>
                      );
                    })}
                  </div>
                  <div style={{ display: 'flex' }}>
                    <Tabs
                      activeKey={this.state.activeKey}
                      tabPosition={'left'}
                      onChange={this.handleNjTabChange}
                    >
                      <TabPane tab={'下咽'} key={'1'}>
                        <Tree
                          checkable
                          onCheck={this.onCheckHandle(treeOptions[0])}
                          checkedKeys={[...njzd['1']]}
                        >
                          {treeOptions[0]}
                        </Tree>
                      </TabPane>
                      <TabPane tab={'食管'} key={'2'}>
                        <Tree
                          checkable
                          onCheck={this.onCheckHandle(treeOptions[1])}
                          checkedKeys={[...njzd['2']]}
                        >
                          {treeOptions[1]}
                        </Tree>
                      </TabPane>
                      <TabPane tab={'贲门'} key={'3'}>
                        <Tree
                          checkable
                          onCheck={this.onCheckHandle(treeOptions[2])}
                          checkedKeys={[...njzd['3']]}
                        >
                          {treeOptions[2]}
                        </Tree>
                      </TabPane>
                      <TabPane tab={'胃'} key={'4'}>
                        <Tree
                          checkable
                          onCheck={this.onCheckHandle(treeOptions[3])}
                          checkedKeys={[...njzd['4']]}
                        >
                          {treeOptions[3]}
                        </Tree>
                      </TabPane>
                      <TabPane tab={'十二指肠'} key={'5'}>
                        <Tree
                          checkable
                          onCheck={this.onCheckHandle(treeOptions[4])}
                          checkedKeys={[...njzd['5']]}
                        >
                          {treeOptions[4]}
                        </Tree>
                      </TabPane>
                    </Tabs>
                  </div>
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={24}>
                <Form.Item labelCol={{ span: 2, offset: 0 }} label="内镜报告单">
                  <ReportCard
                    imagePreview={true}
                    emptyMsg={'暂无内镜报告单,请上传内镜报告单'}
                    uploadBtnLabel={'上传内镜报告单'}
                    fileUrl={this.state.form.reportFileUrl}
                    isUploading={this.state.isUploading}
                    beforeUpload={this.handleUploadBefore}
                    onChange={this.handleBlUploadChange}
                    onDelClick={this.handleDelBlImage}
                  ></ReportCard>
                </Form.Item>
              </Col>
            </Row>

            {/* <div className={style.body}>
                            <div className={style.bodyItem}>
                                <div className={style.bodyItemLeft}>
                                    <p>内镜诊断</p>
                                </div>
                                <div className={style.bodyItemRight} >

                                </div>
                            </div>
                            <div className={style.bodyItem}>
                                <div className={style.bodyItemLeft}>
                                    <p>内镜报告单</p>
                                </div>
                                <div className={style.bodyItemRight} >

                                </div>
                            </div>
                        </div> */}
          </Form>
        </Modal>
      </div>
    );
  }
}
